layui.use(['layer','form'], function() {
    var layer = layui.layer, form = layui.form;
    initArea();$(window).bind('resize',function(){initArea();});
    var setting = {view: {}, check: {enable: true}, data: {simpleData: {enable: true,pIdKey:'parentId'}}, edit: {enable: false}};
    var $menuTree = $("#menuTree");
    var id = getUrlParam("id");
    var fn = {
        menuMaps:{},
        initAllMenu:function () {
            $menuTree.html('<img src="/images/load.gif"/>');
            $.get(rurl('scm/menu/getAllTypeMenu'),{},function (res) {
                if(isSuccess(res)){
                    var data = res.data,nodes = [];
                    nodes.push({id:'0', parentId:'-1', name:'所有操作', open:true,checked:true});
                    $.each(data,function (i,o) {
                        o['parentId']=isEmpty(o.parentId)?'0':o.parentId;
                        if(o.type<2){o['open']=true;}
                        if(fn.menuMaps[o.id]){
                            o['checked'] = true;
                        }
                        nodes.push(o);
                    });
                    $.fn.zTree.init($menuTree, setting, nodes);
                }
            });
        },
        roleDetail:function () {
            show_loading();
            $.get(rurl('scm/role/detail'),{'id':id},function (res) {
                if(isSuccess(res)){
                    var data = res.data;
                    data['switchDisabled'] = !data.disabled;
                    data['preId'] = data.id;
                    form.val('form',data);
                    $.each(data.menus,function (i,o) {
                        fn.menuMaps[o.id] = true;
                    });
                    fn.initAllMenu();
                }
            });
        }
    }
    fn.roleDetail();

    form.on('switch(switchDisabled)', function(data){
        $('#disabled').val(!this.checked);
    });

    $('#openAll').click(function (){var treeObj = $.fn.zTree.getZTreeObj("menuTree");treeObj.expandAll(true);});
    $('#closeAll').click(function (){var treeObj = $.fn.zTree.getZTreeObj("menuTree");treeObj.expandAll(false);});
    form.on('submit(save-btn)', function(data){
        var mids = obtainMenuCheck();
        $('#menuIds').val(mids.join(','));
        if(mids.length==0){
            confirm_inquiry('您确定不需要给此角色授予操作权限？',function () {saveRole();});
            return false;
        }
        saveRole();
        return false;
    });
});
function saveRole() {
    formSub('scm/role/edit',function (res) {
        parent.reloadList();
        closeThisWin('修改成功');
    });
}
function obtainMenuCheck() {
    var treeObj = $.fn.zTree.getZTreeObj("menuTree"), nodes = treeObj.getCheckedNodes(true),mids=[];
    for(var i=0;i<nodes.length;i++){
        var mid = nodes[i].id;
        if(!isEmpty(mid)&&mid!='0'){
            mids.push(mid)
        }
    }
    return mids;
}
function initArea() {
    $('.role-area').css({'height':($(window).height()-119)+'px'});
}